package com.wuneng.ircontrol.myUtil.okhttp;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.wuneng.commonlibrary.net.OkNetUtil;
import com.wuneng.commonlibrary.util.NetUtils;
import com.google.gson.reflect.TypeToken;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.File;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import com.wuneng.ircontrol.common.util.CariGson;
import com.wuneng.ircontrol.common.util.Constants;


/**
 * Created by ljm on 2017/7/20.
 */

public class OkServiceExecute {
    private static String url = "";

    public static OkServiceExecute getInstance() {
        return Nested.sin;
    }

    private String TAG = "OkServiceExecute";

    // 在第一次被引用时被加载
    static class Nested { // 静态内部类
        private static OkServiceExecute sin = new OkServiceExecute();
    }

    public void doPost(String url, Map<String, String> params, final OkPostListener okPostListener) {
        Log.e(TAG, "http://" + Constants.SERVER.SERVER_IP + url);
        Log.e(TAG, "request data:" + CariGson.getInstance().toJson(params));
        OkHttpUtils.post().params(params).url("http://" + Constants.SERVER.SERVER_IP + url).addHeader("domain", Constants.DOMAIN).addHeader("acceptdomain", Constants.ACCEPTDOMAIN).addHeader("userid", Constants.UserID)
                .addHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8").build().connTimeOut(5 * 1000).writeTimeOut(2 * 60 * 1000).readTimeOut(2 * 60 * 1000).execute(new StringCallback() {

            @Override
            public void onError(Call call, Exception e, int id) {
                okPostListener.onError("网络连接异常，请检查网络状态");
            }

            @Override
            public void onResponse(String response, int id) {
                response(response, okPostListener);
            }
        });

    }

    /**
     * 上传附件
     */
    public void upLoadFile(File file, Map<String, String> params, final OkPostListener okPostListener) {
        OkHttpUtils.post().params(params).addFile("portrait", file.getName(), file).url("http://" + Constants.SERVER.SERVER_IP).
                addHeader("Content-type", "multipart/form-data").addHeader("domain", Constants.DOMAIN).addHeader("acceptdomain", Constants.ACCEPTDOMAIN).build().connTimeOut(2 * 60 * 1000).writeTimeOut(2 * 60 * 1000).readTimeOut(2 * 60 * 1000).execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                okPostListener.onError("图片上传失败，请重新上传");
            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    JSONArray array = new JSONArray(response);
                    if (array.length() > 0) {
                        okPostListener.onSuccess("", "");
                    } else {
                        okPostListener.onError("图片上传失败，请重新上传");
                    }
                } catch (JSONException e) {
                    okPostListener.onError("图片上传失败，请重新上传");
                    e.printStackTrace();
                }

            }

        });
    }


    /**
     * get
     *
     * @param okPostListener
     */

    public void doGet(String url, final Map map, final OkPostListener okPostListener) {
        Log.e(TAG, "http://" + Constants.SERVER.SERVER_IP + url);
        Log.e(TAG, "request data:" + CariGson.getInstance().toJson(map));
        OkHttpUtils.get().url("http://" + Constants.SERVER.SERVER_IP + url).addHeader("userId", Constants.UserID).addHeader("acceptdomain", Constants.ACCEPTDOMAIN).params(map).addHeader("domain", Constants.DOMAIN).build().
                connTimeOut(5000).readTimeOut(30000).writeTimeOut(15000).execute(new StringCallback() {

            @Override
            public void onResponse(String response, int id) {
                // TODO Auto-generated method stub
                response(response, okPostListener);
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                okPostListener.onError("连接异常");
            }

        });

    }

    public static void downFile(Context context, String url, String path, String fileName, final OkNetUtil.OkHttpDownFileCallBack
            httpCallBack, int id) {
        if (NetUtils.isNetworkConnected(context)) {
            OkHttpUtils
                    .get()
                    .url(url)
                    .id(id)
                    .build()
                    .execute(new FileCallBack(path, fileName) {

                        @Override
                        public void inProgress(float progress, long total, int id) {
                            httpCallBack.process(progress, total, id);
                        }

                        @Override
                        public void onError(Call call, Exception e, int id) {
                            httpCallBack.error(call, e, id);
                        }

                        @Override
                        public void onResponse(File response, int id) {
                            httpCallBack.fileResponse(response, id);
                        }
                    });
        } else {
            httpCallBack.onNoNetWork(id);
            return;
        }
    }


    /**
     * 上传多附件
     */
    public void upLoadMultiFile(String url, Map params, List<File> file, final OkPostListener okPostListener) {
        PostFormBuilder postFormBuilder = OkHttpUtils.post();
        for (int i = 0; i < file.size(); i++) {
            postFormBuilder.addFile("file", file.get(i).getName(), file.get(i));
        }

        postFormBuilder.url("http://" + Constants.SERVER.SERVER_IP + url).params(params).build().connTimeOut(60000).writeTimeOut(60000).readTimeOut(60000).execute(new StringCallback() {

            @Override
            public void onResponse(String response, int id) {
                response(response, okPostListener);
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                okPostListener.onError("连接异常");
            }

        });
    }


    /**
     * 接口返回的操作以及回调
     */
    private void response(String response, OkPostListener okPostListener) {
        Log.e(TAG, "Resonse data：" + response);
        ActionResponse actionResponse = CariGson.getInstance().fromJson(response, new TypeToken<ActionResponse>() {
        }.getType());
        if (actionResponse.getCode() == 1) {
            if (actionResponse.getData() == null) {
                okPostListener.onSuccess(response, actionResponse.getMessage());
            } else {
                if (actionResponse.getData().getClass().getSimpleName().equals("String")) {
                    okPostListener.onSuccess(actionResponse.getData() + "", actionResponse.getMessage());
                } else {
                    okPostListener.onSuccess(CariGson.getInstance().toJson(actionResponse.getData()), actionResponse.getMessage());
                }
            }

        } else {
            if (TextUtils.isEmpty(actionResponse.getMessage())) {
                okPostListener.onError(response);
            } else {
                okPostListener.onError(actionResponse.getMessage());
            }

        }

    }
}
